<template>
	<view class='container'>
		<map id='map' :scale='map.scale' :style="{width:`${map_width}`, height:`${map_height}` }" :longitude='map.longitude'
		 :latitude='map.latitude' :markers='map.markers' @regionchange='mapChange' @markertap="map_click" show-location>
			<cover-view class="search-box">
				<cover-view class="search" @click="jump()">
					<cover-view class="iconfont iconsousuo"></cover-view>
					<cover-view>请输入您要寻找的地址</cover-view>
				</cover-view>
			</cover-view>
			<cover-view class="tishi-box" v-if="!is_show" :style="{ opacity: `${title_text_optcity}`,top:`${title_box}` }">
				{{address_title}}
			</cover-view>
			<cover-image :src="$util.img('upload/uniapp/address_icon1.png')" :style="{top:`${img_box}` }" v-if="is_show" class="icon-img"></cover-image>
		</map>
		<view class='footer' :style="{height:`${footer_height}`, marginTop:`${marTop}`}">
			<view class="line" v-if="marTop=='-150px'" @click="height_change()"></view>
			<view class="up-img-box" v-if="marTop=='-20px'" @click="height_change()">
				<image class="up-img" :src="$util.img('upload/uniapp/up.png')" mode="widthFix"></image>
			</view>

			<scroll-view scroll-y id="comment" ref="comment" class='scroll' :style="{height:`${footer_height}`}" :scroll-top='scrollTop'
			 scroll-with-animation>
				<view class="address" :class="newaddress.cl_id==check_cl_id?'active-now':''" @click="check_address(newaddress)"
				 v-if="chooseed">
					<text class="abs-text">当前自提点</text>
					<image :src="$util.img(newaddress.community_img)" mode="aspectFill"></image>
					<view class="address-detail">
						<view class="address-title">
							<text class="title">{{newaddress.community}}</text>
							<text class="iconfont " :class="newaddress.cl_id==check_cl_id?'iconyuan_checked color-base-text':'iconyuan_checkbox'"></text>
						</view>
						<view class="address-size" v-if="newaddress.distance">
							<image src="../../../static/address.png" mode="widthFix"></image>
							<text>距您{{newaddress.distance}}</text>
						</view>
						<view class="address-area">
							<text>地址:</text>
							<text>{{newaddress.full_address}}</text>
						</view>
					</view>
				</view>

				<view class="scroll-title">
					当前定位附近的提货点
				</view>
				<view class="address" v-for="(item,index) in list" :key="index" :class="item.cl_id==check_cl_id?'active-now':''"
				 @click="check_address(item)">
					<text class="abs-text" v-if="index==0">距您最近</text>
					<image :src="$util.img(item.community_img)" mode="aspectFill"></image>
					<view class="address-detail">
						<view class="address-title">
							<text class="title">{{item.community}}</text>
							<text class="iconfont " :class="item.cl_id==check_cl_id?'iconyuan_checked color-base-text':'iconyuan_checkbox'"></text>
						</view>
						<view class="address-size" v-if="item.distance">
							<image src="../../../static/address.png" mode="widthFix"></image>
							<text>距您{{item.distance}}</text>
						</view>
						<view class="address-area">
							<text>地址:</text>
							<text>{{item.full_address}}</text>
						</view>
					</view>
				</view>
				<view class="fill-box"></view>
			</scroll-view>
			<view class="submit-box">
				<button type="primary" @click="submit()">确认提货点</button>
			</view>
		</view>
		<loading-cover ref="loadingCover"></loading-cover>
	</view>
</template>
<script>
	const app = getApp()




	export default {
		data() {
			return {
				detail: '',
				map_width: '100%',
				map_height: '430px',
				title_box: '21%',
				img_box: '40%',
				footer_height: '58vh',
				marTop: '-150px',
				map: {
					latitude: 39.911,
					longitude: 116.39741,
					// iconPath: '../../../static/address.png',
					width: 20,
					height: 30,
					// iconPath: this.$util.img('upload/uniapp/address_icon1.png'),
					scale: 17,
					markers: []
				},
				new: { //当前位置
					lat: 39.911,
					log: 116.39741,
				},
				title_text_optcity: 0,
				is_show: false, //定位图标，自提点名称提示
				list: [],
				newaddress: {},
				address_title: '',
				address: {
					title: '',
					address: ''
				},
				checked: 0,
				scrollTop: 0,
				mapStatus: 1, // 控制选择地址时 地图不加载附近列表
				addredd_id: 0,
				token: '',
				check_cl_id: '',
				back: '/otherpages/community/community_choose/community_choose',
				chooseed: false, //是否有当前自提点
				mapCtx: '',
				type: 0, //进入类型
				is_first: true, //是否第一次进去，需要刷新地图
				is_refund: true, //是否刷新地图
				// query: ''
			}
		},
		created() {
			uni.setNavigationBarTitle({
				title: '社区搜索'
			})
		},
		onLoad(option) {
			if (uni.getStorageSync('token')) {
				this.token = uni.getStorageSync('token')
				if (option.lat_old && option.log_old && !option.latng) {
					// 带有自提点信息进来
					this.type = 1
					this.is_show = true
					this.chooseed = true
					this.getlocal()
				} else if (option.lat_old && option.log_old && option.latng) {
					// 搜索回来的
					let newlatng = option.latng
					this.map.latitude = newlatng.split(',')[0]
					this.map.longitude = newlatng.split(',')[1]
					this.new.log = newlatng.split(',')[1]
					this.new.lat = newlatng.split(',')[0]
					this.is_show = true
					this.getAddressList()
					this.chooseed = true
					this.getLeaderAddress()
				} else {
					this.type = 2
					this.getlocal()
					// 没有信息进入
					this.chooseed = false
				}
				// }
				// )
			} else {
				this.$util.redirectTo('/pages/member/index/index');
			}
			// this.query = uni.createSelectorQuery().in(this);
		},
		methods: {
			height_change() {
				if (this.marTop == '-150px') {
					this.marTop = '-20px'
					this.footer_height = '34vh'
					this.map.scale--
					if (!this.is_show) this.title_show()
				} else {
					this.marTop = '-150px'
					this.footer_height = '58vh'
					this.map.scale++
					if (!this.is_show) this.title_show()
				}
			},
			getlocal() {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						this.new.lat = res.latitude
						this.new.log = res.longitude
						this.map.latitude = res.latitude
						this.map.longitude = res.longitude
						if (this.type == 1) {
							this.getLeaderAddress() //团长信息
							this.setData({
								position: {
									latitude: res.latitude,
									longitude: res.longitude
								}
							})
							this.getAddressList(1) //附近位置
						} else {
							this.getAddressList(0) //附近位置
						}
					},
				});
				setTimeout(() => {
					if (this.new.lat == 39.911 && this.new.log == 116.39741) {
						this.IPLoca()
					}
				}, 500)

			},
			IPLoca() {
				this.$api.sendRequest({
					url: '/api/Address/ipLocation',
					success: res => {
						if (res.code == 0) {
							this.new.lat = res.data.location.lat
							this.new.log = res.data.location.lng
							this.map.latitude = res.data.location.lat
							this.map.longitude = res.data.location.lng	
													
							this.setData({
								position: {
									latitude: res.data.location.lat,
									longitude: res.data.location.lng
								}
							})
						}
						if (this.type == 1) {
							this.getLeaderAddress() //团长信息
							this.getAddressList(1) //附近位置
						} else {
							this.getAddressList(0) //附近位置
						}
					}
				});
			},
			// 地图直接点击
			map_click(e) {
				// #ifdef H5
				let map_index = e.detail.markerId
				let _group = this.map.markers
				for (let item in _group) {
					if (_group[item].id == map_index) {
						if (this.type == 1) {
							if (item != 0) {
								this.scrollTop = 120 + (parseInt(item) + 1) * 110
							} else {
								this.scrollTop = 120
							}
						} else {
							if (item != 0) {
								this.scrollTop = (parseInt(item) + 1) * 110
							} else {
								this.scrollTop = 10
							}
						}
					}
				}
				let map_item = this.map.markers[map_index]
				this.map.latitude = map_item.latitude
				this.map.longitude = map_item.longitude
				this.address_title = map_item.community
				this.is_show = false
				this.title_show()
				this.check_cl_id = this.list[map_index].cl_id
				// #endif
			},
			// 点击切换
			check_address(e) {
				this.check_cl_id = e.cl_id
				// this.map.latitude = e.latitude
				// this.map.longitude = e.longitude
				// this.address_title = e.address
				// this.setData({
				// 	position: {
				// 		latitude: e.latitude,
				// 		longitude: e.longitude
				// 	}
				// })
				// this.getAddressList(0)
				// this.is_show = false
				// this.title_show()
			},
			// 拖动
			mapChange(e) {
				this.is_show = true
				let that = this
				clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					if (e.type == 'end') {
						this.is_refund = false
						that.mapCtx = uni.createMapContext('map')
						that.mapCtx.getCenterLocation({
							success: res => {
								that.setData({
									position: {
										latitude: res.latitude,
										longitude: res.longitude
									}
								})
								if (that.mapStatus) { // 防止地图点击时 进行多次加载
									that.getAddressList(1)
								} else {
									that.mapStatus = 1
								}
								this.map.latitude = res.latitude,
									this.map.longitude = res.longitude
							}
						})
					}
				}, 200)
			},
			// 获取当前
			getLeaderAddress() {
				this.$api.sendRequest({
					url: '/api/community/getMemberCommunity',
					data: {
						token: this.token,
						longitude: this.new.log,
						latitude: this.new.lat
					},
					success: res => {
						if (res.code == 0) {
							res.data.full_address = res.data.full_address.replace(/,/g, "")
							this.newaddress = res.data
							this.check_cl_id = this.newaddress.cl_id
							this.newaddress.distance = this.conversion_util(this.newaddress)
						}
						
					}
				});
			},
			conversion_util(e) {
				let _distance = e.distance
				let newDistance = ''
				if (_distance < 1) {
					newDistance = parseFloat(_distance) * 1000 + '米'
				} else {
					newDistance = _distance + '公里'
				}
				return newDistance
			},
			// 附近自提点信息
			getAddressList(s = 0) {
				let position = this.position
				let _lat = ''
				let _log = ''
				if (s == 0) {
					_lat = this.new.lat
					_log = this.new.log
				} else {
					_lat = position.latitude
					_log = position.longitude
				}
				// 请求
				this.$api.sendRequest({
					url: '/api/community/leaderPage',
					data: {
						token: this.token,
						latitude: _lat,
						longitude: _log
					},
					success: res => {
						if (res.code == 0) {
							res.data.list.forEach(item => {
								item.full_address = item.full_address.replace(/,/g, "")
								item.distance = this.conversion_util(item)
								if (item.cl_id == this.newaddress.cl_id) {
									this.newaddress.distance = item.distance
								}
							})
							this.list = res.data.list
							//处理点位信息
							let newarray = []
							for (let s in this.list) {
								newarray.push({
									id: s,
									latitude: this.list[s].latitude,
									longitude: this.list[s].longitude,
									width: 22,
									height: 30,
									iconPath: this.$util.img('upload/uniapp/address_icon2.png'),
									community: this.list[s].community
								})
							}

							this.map.markers = newarray

							// 处理点位不显示
							if (this.is_first) {
								this.is_first = !this.is_first
								this.mapCtx = uni.createMapContext('map')
								this.mapCtx.getCenterLocation({
									success: res => {
										this.setData({
											position: {
												latitude: res.latitude,
												longitude: res.longitude
											}
										})
										this.getAddressList(0)
									}
								})
							}
						}
						if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
					}
				});
			},
			jump() {
				// #ifdef MP || APP-PLUS
				uni.chooseLocation({
					success: res => {
						this.map.latitude = res.latitude;
						this.map.longitude = res.longitude;
						this.map.address = res.name;
						// this.getAddress(res.latitude + ',' + res.longitude);
					},
					fail(res) {
						uni.getSetting({
							success: function(res) {
								var statu = res.authSetting;
								if (!statu['scope.userLocation']) {
									uni.showModal({
										title: '是否授权当前位置',
										content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
										success(tip) {
											if (tip.confirm) {
												uni.openSetting({
													success: function(data) {
														if (data.authSetting['scope.userLocation'] === true) {
															this.$util.showToast({
																title: '授权成功'
															});
															//授权成功之后，再调用chooseLocation选择地方
															setTimeout(function() {
																uni.chooseLocation({
																	success: data => {
																		this.map.latitude = data.latitude;
																		this.map.longitude = data.longitude;
																		this.map.address = data.name;
																		// this.getAddress(res.latitude + ',' + res.longitude);
																	}
																});
															}, 1000);
														}
													}
												});
											} else {
												this.$util.showToast({
													title: '授权失败'
												});
											}
										}
									});
								}
							}
						});
					}
				});
				// #endif
				// #ifdef H5 
				// 'http://localhost:8080'
				// let backurl = + + this.back;
				let backurl = this.$config.h5Domain + this.back + '?lat_old=' + this.map.latitude + '&log_old=' + this.map.longitude +
					'&token=' + this.token;


				window.location.href = 'https://apis.map.qq.com/tools/locpicker?search=1&type=0&backurl=' + encodeURIComponent(
					backurl) + '&key=' + this.$config.mpKey + '&referer=myapp';
				// #endif
			},
			setData(obj) {
				Object.assign(this, obj)
			},
			title_show() {
				this.title_text_optcity = 0
				setTimeout(() => {
					this.title_text_optcity = .2
				}, 300)
				setTimeout(() => {
					this.title_text_optcity = .4
				}, 400)
				setTimeout(() => {
					this.title_text_optcity = .6
				}, 500)
				setTimeout(() => {
					this.title_text_optcity = .8
				}, 600)
				setTimeout(() => {
					this.title_text_optcity = 1
				}, 700)
			},
			submit() {
				this.$api.sendRequest({
					url: '/api/community/updateMemberCommunity',
					data: {
						cl_id: this.check_cl_id
					},
					success: res => {
						if (res.code == 0) {
							uni.showToast({
								title: '设置成功',
								icon: 'none'
							})
							uni.setStorage({
								key: 'community_address',
								data: {
									community_id: this.check_cl_id
								},
								success: function() {
									uni.navigateBack()
								}
							});



							// uni.setStorageSync('community_address', {
							// 	community_id: this.check_cl_id
							// });
							// setTimeout(() => {
							// 	uni.navigateBack()
							// }, 800)
						}
					}
				});
			},
			// getAddress() {
			// 	console.log('getAddress')
			// 	let that = this
			// 	uni.getLocation({
			// 		type: 'gcj02',
			// 		success: function(res) {
			// 			console.log(res)
			// 			let map = that.data.map
			// 			map.longitude = res.longitude
			// 			map.latitude = res.latitude
			// 			that.getWidthHeight(e => {
			// 				map.controls[0].position.top = e.height / 2 - 35
			// 				map.controls[0].position.left = e.width / 2 - 20
			// 				that.setData({
			// 					map: map,
			// 					position: {
			// 						longitude: res.longitude,
			// 						latitude: res.latitude
			// 					}
			// 				})
			// 				that.getAddressList(1)
			// 			})
			// 		},
			// 	})
			// },
			// getWidthHeight() {
			// 	console.log('getWidthHeight')
			// 	var query = uni.createSelectorQuery()
			// 	query.select('#map').boundingClientRect()
			// 	query.exec(res => {
			// 		console.log(res)
			// 	})
			// },
			// bindAddress(index) {
			// 	console.log('bindAddress')
			// 	let list = this.list
			// 	let map = this.map
			// 	map.latitude = list[index].location.lat
			// 	map.longitude = list[index].location.lng
			// 	this.setData({
			// 		map: map,
			// 		checked: index,
			// 		address: list[index],
			// 		mapStatus: 0
			// 	})
			// },

		}
	}
</script>

<style lang="scss">
	.container {
		position: relative;

		.footer {
			border-top-left-radius: $border-radius;
			border-top-right-radius: $border-radius;
			margin-top: -50rpx;
			background-color: white;
			position: fixed;
			top: calc(100vh-300rpx);
			left: 0;
			height: 60vh;
			width: 100%;
			transition: all .5s;

			.line {
				width: 80rpx;
				height: 12rpx;
				margin: 20rpx auto;
				border-radius: $border-radius;
				background-color: #EEEEEE;
			}

			.up-img-box {
				display: flex;
				align-items: center;
				margin: 10rpx 0;

				.up-img {
					margin: 0 auto;
					width: 80rpx;
				}
			}


			.scroll-title {
				color: $color-title;
				font-size: 30rpx;
				margin-left: $margin-both;
			}

			.scroll {
				height: 60vh;
				transition: all .5s;
			}

			.address {
				display: flex;
				align-items: center;
				background-color: #FCFCFC;
				border: 1px solid $color-line;
				padding: $padding;
				margin: $margin-updown $margin-both;
				border-radius: $border-radius;
				position: relative;
				box-sizing: border-box;
				// height: 220rpx;

				.abs-text {
					position: absolute;
					top: 0;
					left: 0;
					background-color: #FF4544;
					color: white;
					z-index: 9;
					line-height: 1.6;
					border-top-left-radius: $border-radius;
					border-bottom-right-radius: $border-radius;
					font-size: 20rpx;
					padding: 0 10rpx;
				}

				image {
					width: 160rpx;
					height: 160rpx;
					border-radius: $border-radius;
				}

				.address-detail {
					margin-left: 16rpx;
					display: flex;
					align-items: flex-start;
					flex-direction: column;
					justify-content: space-around;
					width: 500rpx;
					// height: 200rpx;

					view {
						// height: 44rpx;
					}

					.address-title {
						width: 100%;
						display: flex;
						align-items: center;
						justify-content: space-between;

						.title {
							font-size: $font-size-base;
							color: $color-title;
						}

						.iconfont {
							color: $color-sub;
							font-size: 34rpx;
						}

						.iconyuan_checked {
							color: #FF4544;
						}
					}

					.address-size {
						image {
							margin-right: 6rpx;
							width: 24rpx;
						}

						text {
							line-height: 1.0;
							color: $color-sub;
							font-size: $font-size-sub;
						}
					}

					.address-area {
						text {
							line-height: 1;
							font-size: $font-size-sub;
						}
					}
				}
			}

			.fill-box {
				padding-top: 30rpx;
				width: 100%;
				height: 150rpx;
			}


			.active-now {
				background-color: rgba(#FF4544, .06);
				border: 1rpx solid rgba(#FF4544, .4);
			}

			.submit-box {
				background-color: white;
				// border-top: 2rpx solid $color-line;
				padding: $padding;
				box-sizing: border-box;
				position: fixed;
				bottom: 0;
				left: 0;
				width: 100%;
				height: 130rpx;
				z-index: 99;

				button {
					line-height: 94rpx;
					font-size: $font-size-base;
					letter-spacing: 2rpx;
					border-radius: 60rpx;
					margin: 0;
					height: 94rpx;
				}
			}
		}
	}

	.map {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.search-box {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 70rpx;
		margin-top: 20rpx;
		padding: 0 30rpx;
		box-sizing: border-box;

		.search {
			display: flex;
			align-items: center;
			background-color: #F8F8F8;
			border-radius: 50rpx;
			width: 100%;
			height: 100%;
			padding: 0 20rpx;

			text {
				height: 100%;
				line-height: 74rpx;
				font-size: 30rpx;
			}

			text:last-child {
				margin-left: 10rpx;
				height: 100%;
				line-height: 70rpx;
				font-size: $font-size-base;
				color: $color-sub;
			}
		}
	}

	.tishi-box {
		display: block;
		position: fixed;
		top: 10%;
		left: 33%;
		width: 30%;
		text-align: center;
		background-color: white;
		padding: $padding;
		border-radius: $border-radius;
	}

	.icon-img {
		width: 26px;
		height: 34px;
		display: block;
		position: fixed;
		top: 28%;
		left: 50%;
		transform: translate(-50%, -50%);
		margin-top: -70px;
	}
</style>
